package club.xiaojiawei.array;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 2022/4/21 19:34
 * @question 59.螺旋矩阵II
 * @description 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class SpiralMatrixII59 {
    public static void main(String[] args) {
        int[][] ints = generateMatrix(6);
        for (int i = 0; i < ints.length; i++) {
            for (int i1 = 0; i1 < ints[i].length; i1++) {
                System.out.print(ints[i][i1]+"\t");
            }
            System.out.println();
        }
    }

    /**
     * 模拟
     * @param n
     * @return
     */
    public static int[][] generateMatrix(int n) {
        int size = n * n, incrementX = 0, incrementY = 1, nowX = 0, nowY = -1, count = 1, temp;
        int[][] arr = new int[n][n];
        while (count <= size) {
            while (nowY + incrementY >= n || nowX + incrementX >= n || nowY + incrementY < 0 || nowX + incrementX < 0 || arr[nowX + incrementX][nowY + incrementY] != 0 ){
                temp = incrementX;
                incrementX = incrementY;
                incrementY = -temp;
            }
            arr[nowX += incrementX][nowY += incrementY] = count++;
        }
        return arr;
    }

    /**
     * 民间-按层模拟
     * @param n
     * @return
     */
    public static int[][] generateMatrix1(int n) {
        int l=0,r=n-1,t=0,b=n-1;
        int[][] mat = new int[n][n];
        int num=1,tar=n*n;
        while(num<=tar){
            for(int i = l; i <= r; i++){
                mat[t][i] = num++;
            }
            t++;
            for(int i = t; i <= b; i++){
                mat[i][r] = num++;
            }
            r--;
            for(int i = r; i >= l; i--){
                mat[b][i] = num++;
            }
            b--;
            for(int i = b; i >= t; i--){
                mat[i][l] = num++;
            }
            l++;
        }
        return mat;
    }
}